package me.shurufa.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.adapter.ShareThemeAdapter;
import me.shurufa.bean.BookComment;
import me.shurufa.bean.Excerpt;
import me.shurufa.bean.UserInfoEntity;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.glide.AdaptiveBitmapImageViewTarget;
import me.shurufa.widget.popupwindow.SharePopupWindow;
import me.shurufa.widget.wavyline.WavyLineView;

/**
 * 点击图书 获取垂直滑动页面的图书信息部分
 */
public class ShareEditFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.ll_content)
    LinearLayout ll_content;

    @Bind(R.id.tv_content)
    TextView tv_content;

    @Bind(R.id.tv_bookname)
    TextView tv_bookname;

    @Bind(R.id.tv_chapter)
    TextView tv_chapter;

    @Bind(R.id.tv_note_create_time)
    TextView tv_note_create_time;

    @Bind(R.id.tv_user)
    TextView tv_user;

    @Bind(R.id.tv_page_no)
    TextView tv_page_no;

    @Bind(R.id.iv_image)
    ImageView iv_image;

    @Bind(R.id.rv_theme)
    RecyclerView mThemeRcyclerView;

    @Bind(R.id.topWavyline)
    WavyLineView topWavyline;

    @Bind(R.id.bottomWavyline)
    WavyLineView bottomWavyline;

    private String mBookname;
    private Excerpt mExcerpt;
    private BookComment mBookComment;
    private ShareThemeAdapter mThemeAdapter;
    private SharePopupWindow mSharePopupWindow;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static ShareEditFragment newInstance(String bookname, Excerpt digest, BookComment comment) {
        ShareEditFragment fragment = new ShareEditFragment();
        Bundle args = new Bundle();
        args.putString(Constants.ARG_BOOK_TITLE, bookname);
        args.putSerializable(Constants.ARG_SHARE_BEAN_DIGEST, digest);
        args.putSerializable(Constants.ARG_SHARE_BEAN_COMMENT, comment);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_share_edit, container, false);
        ButterKnife.bind(this, view);
        parseArguments();
        return view;
    }

    private void parseArguments() {
        if (null != getArguments()) {
            mBookname = getArguments().getString(Constants.ARG_BOOK_TITLE);
            mExcerpt = (Excerpt) getArguments().getSerializable(Constants.ARG_SHARE_BEAN_DIGEST);
            mBookComment = (BookComment) getArguments().getSerializable(Constants.ARG_SHARE_BEAN_COMMENT);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);

        topWavyline.setAmplitude(2);
        topWavyline.setPeriod((float) (1 * Math.PI / 5));
        topWavyline.setStrokeWidth(2);
        topWavyline.setColor(getResources().getColor(R.color.share_border));

        bottomWavyline.setAmplitude(2);
        bottomWavyline.setPeriod((float) (1 * Math.PI / 5));
        bottomWavyline.setStrokeWidth(2);
        bottomWavyline.setColor(getResources().getColor(R.color.share_border));

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mThemeRcyclerView.setLayoutManager(linearLayoutManager);

        mThemeAdapter = new ShareThemeAdapter();
        mThemeRcyclerView.setAdapter(mThemeAdapter);

        tv_bookname.setText("《" + mBookname + "》");
        if (mExcerpt != null) {
            // 章节
            //NewDigest.MenuInfoEntity menu_info = mExcerpt.menu_title();
            tv_chapter.setText(mExcerpt.menu_title);

            // 页码
            if (mExcerpt.page_num != 0) {
                tv_page_no.setText("P." + mExcerpt.page_num);
            }

            // 用户
            UserInfoEntity user_info = mExcerpt.user_info;

            if (user_info == null || TextUtils.isEmpty(user_info.username)) {
                tv_user.setText("匿名用户的书摘");
            } else {
                tv_user.setText(user_info.username + " 的书摘");
            }

            // 创建时间
            tv_note_create_time.setText(Utils.getFormatTime(mExcerpt.created_at));

            // 内容
            if (Constants.DIGEST_TYPE_TEXT == mExcerpt.type) {
                iv_image.setVisibility(View.GONE);
                tv_content.setVisibility(View.VISIBLE);
                tv_content.setText(mExcerpt.content);
            } else {
                tv_content.setVisibility(View.GONE);
                iv_image.setVisibility(View.VISIBLE);
                Glide.with(getActivity()).load(mExcerpt.screenshot + Constants.THUMB_SUFFIX)
                        .asBitmap()
                        .placeholder(R.drawable.ic_placeholder_digest_image)
                        .error(R.drawable.ic_placeholder_digest_image)
                        .into(new AdaptiveBitmapImageViewTarget(iv_image));
            }
        }

        if (mBookComment != null) {
            // 用户
            tv_user.setText(mBookComment.user_info.username + " 的书评");

            // 创建时间
            tv_note_create_time.setText(Utils.getFormatTime(mBookComment.created_at));

            // 内容
            tv_content.setText(mBookComment.content);
        }
        initListener();
    }

    private void initListener() {
        mThemeAdapter.setOnThemeSelectListener(new ShareThemeAdapter.OnThemeSelectListener() {
            @Override
            public void onThemeSelected(String color) {
                changeTheme(color);
            }
        });
    }

    private void changeTheme(String color) {
        if (ll_content == null) {
            return;
        }
        ll_content.setBackgroundColor(Color.parseColor(color));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    private KProgressHUD kProgressHUD;
    public void openSharePopup(View v) {

        // ShareController.shareToWeibo(getActivity(), ll_content);
        // ShareController.shareToWeChat(1, "", "", "", ScreenShot.compressImage(ScreenShot.getBitmapByView(ll_content)));
        //Utils.launchShareActivity(getActivity(), "title", "", "", "书摘分享", loadBitmapFromView(ll_content));


        if (mSharePopupWindow == null) {
            mSharePopupWindow = new SharePopupWindow(getActivity());
            mSharePopupWindow.init();
        }
        mSharePopupWindow.show(v, 0, ll_content);
    }


    public Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
        Canvas c = new Canvas(screenshot);
        c.translate(-v.getScrollX(), -v.getScrollY());
        v.draw(c);
        return screenshot;
    }

    /**
     * 保存图片
     * @param bm
     * @return
     */
    public String saveBitmap(Bitmap bm) {

        bm = comp(bm);

        String path = "";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (TextUtils.isEmpty(path)) {
                path = Environment.getExternalStorageDirectory().getAbsolutePath();
            }
        }

        File f = new File(path, System.currentTimeMillis()+ ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 10, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f.getAbsolutePath();
    }


    private Bitmap comp(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = image.getHeight();//这里设置高度为800f
        float ww = image.getWidth(); //这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
      // return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
        return bitmap;
    }







    /*private void openDialog() {
        final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
                {
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
                };
        new ShareAction(getActivity()).setDisplayList(displaylist)
                .withText("书入法书摘分享")
                .withTitle("书入法")
                .withTargetUrl("http://www.baidu.com")
                .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                .setListenerList(null, null, null, null, null)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mPlatform == SHARE_MEDIA.WEIXIN) {

                            // doOauthWeixin();
                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.WEIXIN)
                                    .setCallback(null)
                                    .withText("书入法分享")
                                    .withTargetUrl("http://www.baidu.com")
                                    .withMedia(new UMImage(getActivity(), R.drawable.bg_login))
                                    .share();
                        }

                        if (snsPlatform.mPlatform == SHARE_MEDIA.WEIXIN_CIRCLE) {


                            //doOauthWeixinCircle();
                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                    .setCallback(null)
                                    .withText("书入法最强书摘")
                                    .withTargetUrl(null)
                                    .withMedia(new UMImage(getActivity(), R.drawable.bg_login))
                                    .share();
                        }

                        if (snsPlatform.mPlatform == SHARE_MEDIA.SINA) {

                            // doOauthSina();
                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.SINA)
                                    .setCallback(null)
                                    .withText("书入法分享")
                                            //.withTargetUrl("http://www.baidu.com")
                                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                                    .share();
                        }

                        if (snsPlatform.mPlatform == SHARE_MEDIA.QQ) {

                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.QQ)
                                    .setCallback(null)
                                    .withText("书入法分享")
                                            //.withTargetUrl("http://www.baidu.com")
                                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                                    .share();

                        }

                        if (snsPlatform.mPlatform == SHARE_MEDIA.QZONE) {

                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.QZONE)
                                    .setCallback(null)
                                    .withText("书入法分享")
                                            //.withTargetUrl("http://www.baidu.com")
                                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                                    .share();

                        }
                    }
                })
                .open();
    }

    private void doOauthWeixinCircle() {
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN_CIRCLE;
        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListenerWeixinCircle);
    }

    private void doOauthSina() {
        SHARE_MEDIA platform = SHARE_MEDIA.SINA;
        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListenerSina);

    }

    private void doOauthWeixin() {
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListenerWeixin);

    }

    private UMAuthListener umAuthListenerWeixinCircle = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getActivity(), "Authorize succeed", Toast.LENGTH_SHORT).show();
            new ShareAction(getActivity())
                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                    .setCallback(null)
                    .withText("书入法分享")
                            //.withTargetUrl("http://www.baidu.com")
                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                    .share();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getActivity(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getActivity(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    private UMAuthListener umAuthListenerWeixin = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getActivity(), "Authorize succeed", Toast.LENGTH_SHORT).show();
            new ShareAction(getActivity())
                    .setPlatform(SHARE_MEDIA.WEIXIN)
                    .setCallback(null)
                    .withText("书入法分享")
                            //.withTargetUrl("http://www.baidu.com")
                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                    .share();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getActivity(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getActivity(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    private UMAuthListener umAuthListenerSina = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getActivity(), "Authorize succeed", Toast.LENGTH_SHORT).show();
            new ShareAction(getActivity())
                    .setPlatform(SHARE_MEDIA.SINA)
                    .setCallback(null)
                    .withText("书入法分享")
                            //.withTargetUrl("http://www.baidu.com")
                    .withMedia(new UMImage(getActivity(), R.mipmap.ic_launcher))
                    .share();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getActivity(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getActivity(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };*/

}
